package com.snda.sc.utils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.concurrent.atomic.AtomicLong;

/**
 * Redis中Key的生成工具。生成方式和老系统一样，为了和SGI和已经接入的应用兼容。<br>
 * 下面方法参数中uid是HPS生成的影子用户名，snsUid是第三方平台传递来的用户名。
 * 
 * @author <a href="mailto:seenoevil.cn@gmail.com">李曦</a><br/>
 *         Created at: 2012-9-28 上午11:31:17
 */
public abstract class Keys {

	private static final AtomicLong ticketCounter = new AtomicLong();

	/**
	 * 生成储存uid的key。根据code储存uid：plt_code -> uid
	 * 
	 * @param plt
	 * @param code
	 * @return
	 */
	public static String uidKey(String plt, String code) {
		return plt + "_" + code;
	}

	/**
	 * 生成储存code的key。根据uid储存code：plt_uid -> code
	 * 
	 * @param plt
	 * @param uid
	 * @return
	 */
	public static String codeKey(String plt, String uid) {
		return plt + "_" + uid;
	}

	/**
	 * 生成储存UserInfo的key。根据uid储存UserInfo：plt_uid_userinfo -> UserInfo
	 * 
	 * @param plt
	 * @param uid
	 * @return
	 */
	public static String userInfoKey(String plt, String uid) {
		return plt + "_" + uid + "_userinfo";
	}

	/**
	 * 生成储存FriendInfo的key。根据uid储存UserInfo：plt_uid_friendinfo -> FriendInfo
	 * 
	 * @param plt
	 * @param uid
	 * @return
	 */
	public static String friendInfoKey(String plt, String uid) {
		return plt + "_" + uid + "_friendinfo";
	}

	/**
	 * 生成储存ticket的Key。根据uid储存ticket：plt_uid_ticket -> ticket
	 * 
	 * @param plt
	 * @param uid
	 * @return
	 */
	public static String ticketKey(String plt, String uid) {
		return plt + "_" + uid + "_ticket";
	}

	/**
	 * 生成储存GamePlayer的Key。根据uid储存GamePlayer：plt_uid_gameplayer -> GamePlayer
	 * 
	 * @param plt
	 * @param uid
	 * @return
	 */
	public static String gamerPlayKey(String plt, String uid) {
		return plt + "_" + uid + "_gameplayer";
	}

	/**
	 * 生成储存HPS缓存信息的Key。根据uid储存HPS缓存：plt_snsUid_hps -> hps cache
	 * 
	 * @param plt
	 * @param uid
	 * @return
	 */
	public static String hpsCacheKey(String plt, String snsUid) {
		return plt + "_" + snsUid + "_hps";
	}

	/**
	 * 生成token
	 * 
	 * @param uid
	 * @param ticket
	 * @return
	 */
	public static String newCode(String uid, String ticket) {
		String newCode = "";
		try {
			newCode = URLEncoder.encode(ticket, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			Logs.logException("Make token error.", e);
			return null;
		}
		return CommonUtils.md5(uid + newCode);
	}

	/**
	 * 生成ticket
	 * 
	 * @param uid
	 * @return
	 */
	public static String newTicket(String snsUid) {
		ticketCounter.compareAndSet(Long.MAX_VALUE / 2, 0L);
		long ticket = ticketCounter.incrementAndGet();
		return snsUid + "_" + System.currentTimeMillis() + "_" + ticket;
	}
}
